import turtle

p = turtle.Pen()
turtle.tracer(0)  # 关闭动画效果
turtle.bgpic("背景8.gif")  # 设置背景
grid = [[0, 0, 1, 1, 1, 0],
        [0, 0, 1, 4, 1, 1],
        [1, 1, 1, 2, 2, 1],
        [1, 4, 3, 3, 2, 1],
        [1, 1, 2, 2, 2, 1],
        [0, 1, 1, 1, 1, 1]]

# 定义一个二维列表 grid，表示地图的布局。每个数字代表不同的地形或物体：
# 0: 空地
# 1: 墙壁
# 2: 通道
# 3: 箱子
# 4: 目标

width = len(grid[0])  # 列数
height = len(grid)  # 行数
# 计算地图的宽度和高度。width 是第一行的长度（宽度），height 是列表的高度
size = 70  # 大小，尺寸
origin_x = -(width - 1) / 2 * size
origin_y = (height - 1) / 2 * size

player_x = 2
player_y = 4


def draw(pen, img, x, y):
    global origin_x, origin_y, size
    p.goto(origin_x + x * size, origin_y - y * size)
    p.shape(img)
    p.stamp()


def move_up():

    global player_x, player_y, grid
    player_y -= 1
    if player_y < 0:
        player_y += 1
    elif grid[player_y][player_x] == 1:
        player_y += 1

    change_grid()


def move_down():

    global player_x, player_y, grid
    player_y += 1
    if player_y >= height:
        player_y -= 1
        return
    elif grid[player_y][player_x] == 1:
        player_y -= 1
        return
    change_grid()


def move_left():

    global player_x, player_y, grid
    player_x -= 1
    if player_x < 0:
        player_x += 1
        return
    elif grid[player_y][player_x] == 1:
        player_x += 1
        return
    change_grid()



def move_right():

    global player_x, player_y, grid
    player_x += 1
    if player_x >= width:
        player_x-= 1
        return
    elif grid[player_y][player_x] == 1:
        player_x -= 1
        return
    change_grid()


def change_grid():
    global grid, player_x, player_y
    # # 0: 空地
    # # 1: 墙壁
    # # 2: 通道
    # # 3: 箱子
    # # 4: 目标
    if grid[player_y][player_x] == 2:
        grid[player_y][player_x] = 4
    elif grid[player_y][player_x] == 4:
        grid[player_y][player_x] = 3

turtle.onkey(move_up, "Up")
turtle.onkey(move_down,"Down")
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.listen()

tile_shapes = ["空.gif", "岩石.gif", "通道.gif", "箱子.gif", "目标.gif"]
# 定义一个列表，用于放置图像文件
for i in tile_shapes:
    turtle.addshape(i)
# 它遍历tile_shapes中的每个元素。每次循环时，i会被赋予tile_shapes列表中的下一个元素的值。
turtle.tracer(False)
p = turtle.Pen()
turtle.addshape("角色12.gif")
p.penup()  # 抬起画笔,在移动时不会留下任何线条。
turtle.tracer(False)
while True:
    p.clear()
    for i in range(width):
        for j in range(height):
           draw(p, tile_shapes[grid[j][i]], i, j)
    draw(p,"角色12.gif", player_x, player_y)
    p.hideturtle()
    turtle.update()

turtle.done()
